require.config({
  baseUrl: "./script/",
  paths: {
    // three: 'script/../../../lib/three'
    stats: '../../lib/stats.min'
  },
  shim: {
    'script/../../../lib/three': {
      exports: 'THREE'
    }
  }
})

const requestAnimationFrame = window.requestAnimationFrame
  || window.mozRequestAnimationFrame
  || window.webkitRequestAnimationFrame
  || window.msRequestAnimationFrame
window.requestAnimationFrame = requestAnimationFrame;

require(['stats', 'script/../../../lib/three'], function (Stats, THREE) {
  let stat = null
  let scene = null
  let camera = null;

  let renderer = null;
  let mesh = null;

  let id = null;
  let ballMesh = null
  let isMoving = false;
  const maxHeight = 5;
  const ballRadius = 0.5;

  let v = 0;
  let a = -0.01;

  init()
  function init() {
    stat = new Stats();
    stat.domElement.style.position = 'absolute';
    stat.domElement.style.left = '';
    stat.domElement.style.right = '0px';
    stat.domElement.style.top = '0px';
    document.body.appendChild(stat.domElement);

    // 渲染器
    renderer = new THREE.WebGLRenderer();
    renderer.setSize(400, 300);
    document.body.appendChild(renderer.domElement);
    renderer.setClearColor(0x000000);
    scene = new THREE.Scene();

    camera = new THREE.OrthographicCamera(-5, 5, 3.75, -3.75, 0.1, 100);
    camera.position.set(5, 10, 20);
    camera.lookAt(new THREE.Vector3(0, 3, 0));
    scene.add(camera);

    // ball
    ballMesh = new THREE.Mesh(new THREE.SphereGeometry(ballRadius, 16, 8),
      new THREE.MeshLambertMaterial({
        color: 0xffff00
      }));
    ballMesh.position.y = ballRadius;
    scene.add(ballMesh);

    // plane
    const loader = new THREE.TextureLoader()
    const texture = loader.load('../assets/images/chess.png')
    texture.wrapS = texture.wrapT = THREE.RepeatWrapping;
    texture.repeat.set(4, 4);
    const plane = new THREE.Mesh(new THREE.PlaneGeometry(5, 5),
      new THREE.MeshLambertMaterial({map: texture}))
    plane.rotation.x = -Math.PI / 2;
    scene.add(plane);

    const light = new THREE.DirectionalLight(0xffffff)
    light.position.set(10, 10, 15);
    scene.add(light);

    id = requestAnimationFrame(draw);
  }

  function draw() {
    stat.begin();
    if (isMoving) {
      ballMesh.position.y += v;
      if (ballMesh.position.y <= ballRadius) {
        ballMesh.position.y = ballRadius;
        // hit plane
        v = -v * 0.9;
        if (v < a && v > -a) {
          // stop moving
          isMoving = false;
        }
      }
      v += a;
    }

    renderer.render(scene, camera);
    id = requestAnimationFrame(draw);
    stat.end();
  }

  function stop() {
    if (id !== null) {
      cancelAnimationFrame(id);
      id = null;
    }
  }

  function start() {
    if (id === null) {
      id = requestAnimationFrame(draw);
    }
  }

  function drop() {
    isMoving = true;
    ballMesh.position.y = maxHeight;
    v = 0;
  }

  Object.assign(window, {
    stop, start, drop
  })

})
